<script setup>
import MoniterItem from "@/components/MoniterItem.vue";
import "video.js/dist/video-js.css";
import videojs from "video.js";
import "videojs-contrib-hls.js";
import { ref, onMounted, nextTick, inject, reactive, defineEmits } from "vue";

const emit = defineEmits(["makePositon"]);
const $axios = inject("$axios");

// 定义视频ref
const videoRef = ref();

//定时器
let timer = null;
// 当前播放地址index
let videoIndex = 0;

// 视频分类数据分组
const tableData = reactive([]);
// 视频code组
const videoUrls = reactive([]);
// 视频播放器
let videoPlayer = reactive({});

// 获取监控分类数据组
function getBackHomeCount() {
  tableData.splice(0, tableData.length);
  // 初始化播放器
  initPlayer();
  $axios
    .get("/api/camera/firstScreenDevices")
    .then((res) => {
      console.log('视频分类列表', res);
      emit("makePositon", res.data.data);
      res.data.data.forEach((item, index) => {
        if (index === 0) {
          item.clicked = true;
          // 默认选中第一个数据组,根据选中的分类获取视频地址code
          getVideoUrl(item.devices);
        } else {
          item.clicked = false;
        }
        tableData.push(item);
      });
    })
    .then(nextTick);
}

// 点击监控分类
function handleVideoListClickeds(current) {
  clearInterval(timer);
  tableData.forEach((item) => {
    if (item.groupName === current.groupName) {
      item.clicked = true;
      // 根据选中的分类获取视频code
      getVideoUrl(item.devices);
    } else {
      item.clicked = false;
    }
  });
}

//根据点击的分类获取视频code
function getVideoUrl(arr) {
  videoUrls.splice(0, videoUrls.length);
  if (arr.length > 0) {
    arr.forEach((item) => {
      if(item.online){
        videoUrls.push(item.deviceCode);
      }
    });
    scrollVideo();
  } else {
    play('www');
  }
}

// 滚动视频播放地址
function scrollVideo() {
  if(timer){
    clearInterval(timer);
  }
  playVideoFun(0);
  timer = setInterval(() => {
    videoIndex ++;
    if(videoIndex > videoUrls.length-1){
      videoIndex = 0;
    }
    playVideoFun(videoIndex);
  }, 180000);
}

// 获取视频播放地址并播放
function playVideoFun(videoIndex) {
  $axios
    .get("/api/camera/getMediaUrl", {
      params: {
        deviceCode: videoUrls[videoIndex],
      },
    })
    .then((res) => {
      console.log('视频地址', res);
      // 播放视频
      nextTick(() => {
        play(res.data.data.url);
      });
    })
    .then(nextTick);
}

//初始化播放器组
function initPlayer() {
  videoPlayer = videojs(videoRef.value, {
    liveui: true,
    fluid: true, // 扩展以适应其容器的大小
    bigPlayButton: true, // 是否在暂停时显示大的播放按钮，按钮一般默认在左上角
    textTrackDisplay: true,
    posterImage: false, // 是否使用视频的缩略图
    errorDisplay: false,
    controls: true,
    autoplay: true,
    muted: true, //如果为false,视频不会自动播放，这是为了避免噪声扰民
    html5: {
      hlsjsConfig: {
        debug: false,
      },
    },
  }, function (){
      console.log('视频播放器已就绪');
  })
}

function play(url) {
  if (!videoPlayer) {
    log.error('播放器未就绪')
    return;
  }
  ///////////////////////////////
  //获取视频地址并播放
  ///////////////////////////////
  let proxyUrl = covertURL(url);
  //播放视频
  videoPlayer.src({
    src: proxyUrl,
    type: 'application/x-mpegURL'
  });
  videoPlayer.play();
}

function covertURL(originUrl) {
  //本地测试，需要代理，否则会跨域
  if (location.host.indexOf('localhost') >= 0
    || location.host.indexOf('127.0.0.1')  >= 0
    || location.host.indexOf('192.168') >= 0) {
    let domain = 'https://liveplay.hefei.vcn.ctyunxs.cn'
    if (originUrl.startsWith(domain)) {
        return  'http://127.0.0.1/' + originUrl.substring(domain.length + 1)
    }
  }
  return originUrl;
}

onMounted(async () => {
  getBackHomeCount();
  await nextTick;
});
</script>

<template>
  <MoniterItem title="重点场所监控">
    <template #right>
      <div>重点场所监控▲</div>
    </template>
    <template #content>
      <div class="main">
        <div class="left">
          <!-- <video
            id="my-video"
            ref="videoRef"
            class="video-js vjs-default-skin vjs-big-play-centered"
            controls
            preload="auto"
            width="100%"
            height="100%"
            style="height: 100%; width: 100%"
            data-setup="{}"
          >
            <p class="vjs-no-js">
              To view this video please enable JavaScript, and consider
              upgrading to a web browser that
              <a href="https://videojs.com/html5-video-support/" target="_blank"
                >supports HTML5 video</a
              >
            </p>
          </video> -->
          <video id="videoBox" playsinline class="video-js vjs-default-skin vjs-big-play-centered" controls preload="none" data-setup="{}"  width="100%" height="100%" style="height: 100%; width: 100%" ref="videoRef"></video>
        </div>
        <div class="right">
          <!-- <div
            v-for="(item, index) in videoList.arr"
            :key="index"
            :class="{ itemActive: item.clicked }"
            @click="handleVideoListClicked(item)"
          >
            {{ item.tags }}
          </div> -->
          <div
            v-for="(item, index) in tableData"
            :key="index"
            :class="{ itemActive: item.clicked }"
            @click="handleVideoListClickeds(item)"
          >
            {{ item.groupName }}
          </div>
        </div>
      </div>
    </template>
  </MoniterItem>
</template>

<style lang="less" scoped>
.main {
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .left {
    flex: 2;
    padding: 2%;
  }
  .right {
    padding: 2% 2% 2% 0;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    div {
      width: 100%;
      height: 30px;
      text-align: center;
      line-height: 30px;
      font-size: 18px;
      color: #1acfff;
      background-color: #1e89d3;
    }
  }
}
.itemActive {
  color: white !important;
  background-color: #1e89d3;
}
</style>
